<?php

/* * 
 * 项目扩展函数库
 */

/**
 * FirePHP调试类
 * @param string $key
 * @param string $value
 */
function console($key, $value = null) {
    $arg = func_get_args();
    if (count($arg) == 1) {
        FB::info($key, $value);
    } else {
        FB::info($value, $key);
    }
}

/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...') {
    $strlen = strlen($string);
    if ($strlen <= $length)
        return $string;
    $string = str_replace(array(' ', '&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵', ' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
    $strcut = '';
    if (strtolower(C("DEFAULT_CHARSET")) == 'utf-8') {
        $length = intval($length - strlen($dot) - $length / 3);
        $n      = $tn     = $noc    = 0;
        while ($n < strlen($string)) {
            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t <= 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }
            if ($noc >= $length) {
                break;
            }
        }
        if ($noc > $length) {
            $n -= $tn;
        }
        $strcut = substr($string, 0, $n);
        $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
    } else {
        $dotlen      = strlen($dot);
        $maxi        = $length - $dotlen - 1;
        $current_str = '';
        $search_arr  = array('&', ' ', '"', "'", '“', '”', '—', '<', '>', '·', '…', '∵');
        $replace_arr = array('&amp;', '&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;', ' ');
        $search_flip = array_flip($search_arr);
        for ($i           = 0; $i < $maxi; $i++) {
            $current_str = ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
            if (in_array($current_str, $search_arr)) {
                $key         = $search_flip[$current_str];
                $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
            }
            $strcut .= $current_str;
        }
    }
    return $strcut . $dot;
}

function dhtmlspecialchars($string, $flags = null) {
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = dhtmlspecialchars($val, $flags);
        }
    } else {
        if ($flags === null) {
            $string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
            if (strpos($string, '&amp;#') !== false) {
                $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
            }
        } else {
            if (PHP_VERSION < '5.4.0') {
                $string = htmlspecialchars($string, $flags);
            } else {
                if (strtolower(CHARSET) == 'utf-8') {
                    $charset = 'UTF-8';
                } else {
                    $charset = 'ISO-8859-1';
                }
                $string  = htmlspecialchars($string, $flags, $charset);
            }
        }
    }
    return $string;
}

/**
 * 格式化整整数 用于判断是否正确
 * @param string $value
 * @return int
 */
function format_int($value) {
    if (preg_match('/^\d+$/', $value, $arr)) {
        return $arr[0];
    } else {
        return 0;
    }
}

/**
 * 格式化商品价格
 *
 * @access  public
 * @param   float   $price  商品价格
 * @return  string
 */
function format_price($price, $multiple = 100) {
    $price = $price / $multiple;
    $price = number_format($price, 2, '.', '');
    return $price;
}

function dir_path($path) {
    $path = str_replace('\\', '/', $path);
    if (substr($path, -1) != '/')
        $path = $path . '/';
    return $path;
}

function dir_list($path, $exts = '', $list = array()) {
    $path  = dir_path($path);
    $files = glob($path . '*');
    foreach ($files as $v) {
        $fileext = fileext($v);
        if (!$exts || preg_match("/\.($exts)/i", $v)) {
            $list[] = $v;
            if (is_dir($v)) {
                $list = dir_list($v, $exts, $list);
            }
        }
    }
    return $list;
}

function return_url($code) {
    return C('SITEURL') . 'home/pay/respond.html&code=' . $code;
}

function order_pay_status($sn, $value) {
    $cart['status']     = 1;
    $cart['pay_status'] = $value;
    if ($value == 2)
        $cart['pay_time']   = time();
    $r                  = M('Order')->where("sn='{$sn}'")->save($cart);
    //发放金币
    $order              = M('Order')->where("sn='{$sn}'")->find();
    D('UserAccount')->chargeUserAccount($order['userid'], format_price($order['to_glod']), 'RECHARGE', '会员充值: ' . format_price($order['order_amount']) . '元');
    return $r;
}

function reStatus($status = false, $msg = '', $data = array()) {
    $return_arr = array(
        'status' => $status,
        'msg'    => $msg,
        'data'   => $data
    );
    return $return_arr;
}

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
    $string = str_replace('%20', '', $string);
    $string = str_replace('%27', '', $string);
    $string = str_replace('%2527', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('"', '&quot;', $string);
    $string = str_replace("'", '', $string);
    $string = str_replace('"', '', $string);
    $string = str_replace(';', '', $string);
    $string = str_replace('<', '&lt;', $string);
    $string = str_replace('>', '&gt;', $string);
    $string = str_replace("{", '', $string);
    $string = str_replace('}', '', $string);
    return $string;
}

/**
 * 获取当前页面完整URL地址
 */
function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self     = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
    $path_info    = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
    $relate_url   = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . safe_replace($_SERVER['QUERY_STRING']) : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

//URL参数替换
function urlParamChange($key, $old_value, $new_value) {
    $old_url = get_url();
    if (!$new_value) {
        $new_url = trim(str_replace($key . '=' . $old_value, '', $old_url), '&');
    } else if (!$old_value) {
        if (isset($old_value)) {
            $new_url = $old_url . $new_value;
        } else {
            $new_url = $old_url . '&' . $key . '=' . $new_value;
        }
    } else {
        $new_url = str_replace($key . '=' . $old_value, $key . '=' . $new_value, $old_url);
    }
    return $new_url;
}

//页面选择项输出选中css
function hover_css($value, $type = 'area', $css_name = "hover") {
    if ($type == 'area') {
        $search_str = $_REQUEST['aid'];
    } else if ($type == 'cat') {
        $search_str = $_REQUEST['cid'];
    }

    if ($search_str == $value) {
        return $css_name;
    } else {
        return '';
    }
}

/**
 * 转换为安全的纯文本
 *
 * @param string  $text
 * @param boolean $parse_br    是否转换换行符
 * @param int     $quote_style ENT_NOQUOTES:(默认)不过滤单引号和双引号 ENT_QUOTES:过滤单引号和双引号 ENT_COMPAT:过滤双引号,而不过滤单引号
 * @return string|null string:被转换的字符串 null:参数错误
 */
function t($text, $parse_br = false, $quote_style = ENT_NOQUOTES) {
    if (is_numeric($text))
        $text = (string) $text;

    if (!is_string($text))
        return null;

    if (!$parse_br) {
        $text = str_replace(array("\r", "\n", "\t"), ' ', $text);
    } else {
        $text = nl2br($text);
    }

    //$text = stripslashes($text);
    $text = htmlspecialchars($text, $quote_style, 'UTF-8');

    return $text;
}

/**
 * 页面静态碎片调用
 * @param type $post
 * @return type 
 */
function getBlock($post) {
    return M('Block')->where("post='{$post}'")->getField('content');
}

/**
 * 去一个二维数组中的每个数组的固定的键知道的值来形成一个新的一维数组
 * @param $pArray 一个二维数组
 * @param $pKey 数组的键的名称
 * @return 返回新的一维数组
 */
function getSubByKey($pArray, $pKey = "", $pCondition = "") {
    $result = array();
    foreach ($pArray as $temp_array) {
        if (is_object($temp_array)) {
            $temp_array = (array) $temp_array;
        }
        if (("" != $pCondition && $temp_array[$pCondition[0]] == $pCondition[1]) || "" == $pCondition) {
            $result[] = ("" == $pKey) ? $temp_array : isset($temp_array[$pKey]) ? $temp_array[$pKey] : "";
        }
    }
    return $result;
}

/**
 * 建立多级目录
 * @param string $dir
 */
function createDir($dir) {
    return is_dir($dir) or (createDir(dirname($dir)) and mkdir($dir, 0777));
}

/**
 *  杂志目录
 */
function mookList($lists) {
    $lists    = explode('，', $lists);
    $listhtml = '<dl>';
    foreach ($lists as $lv) {
        $listhtml .= '<dt>' . $lv . '</dt>';
    }
    $listhtml .= '</dl>';
    return $listhtml;
}

function getUserName($uid) {
    if ($uid == 0) {
        return '匿名';
    }
    return M('User')->where(array('user_id' => $uid))->getField('uname');
}

function getLinkUrl($id) {
    return M('PayLink')->where(array('link_id' => $id))->getField('url');
}

function getAritcleUrl($id) {
    return U('Home/page/show', array('pid' => $id));
}

function getMookName($id) {
    return M('Mook')->where(array('id' => $id))->getField('title');
}

/*
 * 性别字符串
 */

function sex2Str($sex) {
    switch ($sex) {
        case 'none':
            $str = '保密';
            break;
        case 'man':
            $str = '男';
            break;
        case 'women':
            $str = '女';
            break;
    }
    return $str;
}

//输出安全的html
function h($text, $tags = null) {
    $text = trim($text);
    $text = preg_replace('/<!--?.*-->/', '', $text);
    //完全过滤注释
    $text = preg_replace('/<!--?.*-->/', '', $text);
    //完全过滤动态代码
    $text = preg_replace('/<\?|\?' . '>/', '', $text);
    //完全过滤js
    $text = preg_replace('/<script?.*\/script>/', '', $text);

    $text = str_replace('[', '&#091;', $text);
    $text = str_replace(']', '&#093;', $text);
    $text = str_replace('|', '&#124;', $text);
    //过滤换行符
    $text = preg_replace('/\r?\n/', '', $text);
    //br
    $text = preg_replace('/<br(\s\/)?' . '>/i', '[br]', $text);
    $text = preg_replace('/(\[br\]\s*){10,}/i', '[br]', $text);
    //过滤危险的属性，如：过滤on事件lang js
    while (preg_match('/(<[^><]+) (lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i', $text, $mat)) {
        $text = str_replace($mat[0], $mat[1], $text);
    }
    while (preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat)) {
        $text = str_replace($mat[0], $mat[1] . $mat[3], $text);
    }
    if (empty($tags)) {
        $tags = 'table|tbody|td|th|tr|i|b|u|strong|img|p|br|div|span|em|ul|ol|li|dl|dd|dt|a|alt|h[1-9]?';
        $tags.= '|object|param|embed'; // 音乐和视频
    }
    //允许的HTML标签
    $text = preg_replace('/<(\/?(?:' . $tags . '))( [^><\[\]]*)?>/i', '[\1\2]', $text);
    //过滤多余html
    $text = preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|style|xml)[^><]*>/i', '', $text);
    //过滤合法的html标签
    while (preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i', $text, $mat)) {
        $text = str_replace($mat[0], str_replace('>', ']', str_replace('<', '[', $mat[0])), $text);
    }
    //转换引号
    while (preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2\[\]]+)\2([^\[\]]*\])/i', $text, $mat)) {
        $text = str_replace($mat[0], $mat[1] . '|' . $mat[3] . '|' . $mat[4], $text);
    }
    //过滤错误的单个引号
    // 修改:2011.05.26 kissy编辑器中表情等会包含空引号, 简单的过滤会导致错误
//	while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
//		$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
//	}
    //转换其它所有不合法的 < >
    $text = str_replace('<', '&lt;', $text);
    $text = str_replace('>', '&gt;', $text);
    $text = str_replace('"', '&quot;', $text);
    //$text   =   str_replace('\'','&#039;',$text);
    //反转换
    $text = str_replace('[', '<', $text);
    $text = str_replace(']', '>', $text);
    $text = str_replace('|', '"', $text);
    //过滤多余空格
    $text = str_replace('  ', ' ', $text);
    return $text;
}

//推荐信息
function _roundDazhe($limit = 5) {
    $dazhemod = M('Dazhe');
    $roundDZ  = $dazhemod
            ->order('RAND()')
            ->limit($limit)
            ->select();
    return $roundDZ;
}

/**
 * 会员积分变更行为
 * @param type $action
 * @return string 
 */
function score_action_str($action) {
    switch ($action) {
        case 'FABU_GEZI':
            $str = '发布格子';
            break;
        case 'FABU_CATAD':
            $str = '发布分类广告';
            break;
        case 'FABU_DAZHE':
            $str = '发布打折信息';
            break;
        case 'SYSTEM':
            $str = '系统操作';
            break;
    }
    return $str;
}